package com.winning.ds.common.service.impl;


import com.winning.ds.common.dao.TokenDao;
import com.winning.ds.common.service.TokenService;
import com.winning.ds.common.util.ResponseEntity;
import com.winning.ds.common.util.TokenGenerator;
import com.winning.ds.common.entity.TokenEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.Date;


@Service("TokenService")
public class TokenServiceImpl implements TokenService {
	@Autowired
	private TokenDao tokenDao;
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Override
	public TokenEntity queryByUserId(String zclsh) {
		return tokenDao.queryByUserId(zclsh);
	}

	@Override
	public TokenEntity queryByToken(String token) {
		return tokenDao.queryByToken(token);
	}

	@Override
	public void save(TokenEntity token){
		tokenDao.save(token);
	}
	
	@Override
	public void update(TokenEntity token){
		tokenDao.update(token);
	}

	public ResponseEntity createToken(String zclsh) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//判断是否生成过token
		//TokenEntity tokenEntityOld = queryByUserId(zclsh);
		//if(tokenEntity == null){
		TokenEntity tokenEntity = new TokenEntity();
		tokenEntity.setZclsh(zclsh);
		tokenEntity.setToken(token);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);

			//保存token
			save(tokenEntity);
		/*}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			update(tokenEntity);
		}*/

		ResponseEntity re = ResponseEntity.ok().put("token", token).put("expire", EXPIRE);

		return re;
	}

    @Override
    public void deleteBytoken(String token) {
        tokenDao.deleteByToken(token);
    }
}
